package com.hezuti.common.page;

import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.components.Component;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.opensymphony.xwork2.util.ValueStack;

/**
 * 
 * @author xiaoyu.dou
 * 
 */
public class PageComponent extends Component {

	private Log log = LogFactory.getLog(getClass());

	private String action;

	private String vm;

	private String otherParams;

	private VelocityEngine engine;

	/**
	 * 
	 * @param stack
	 * @param vm
	 * @param action
	 * @param otherParams
	 * @param engine
	 */
	public PageComponent(ValueStack stack, String vm, String action, String otherParams, VelocityEngine engine) {
		super(stack);
		this.action = action;
		this.vm = vm;
		this.otherParams = otherParams == null ? null : "".equals(otherParams.trim()) ? null : otherParams.trim();
		this.engine = engine;
	}

	/**
	 * 
	 */
	public boolean end(Writer writer, String body) {
		try {
			ValueStack stack = getStack();
			PageInfo page = (PageInfo) stack.findValue("page", PageInfo.class);

			int currentPageNo = (int) page.getCurrentPageNo();
			int totalCount = (int) page.getTotalCount();
			int pageSize = (int) page.getPageSize() == 0 ? 1 : (int) page.getPageSize();
			int totalPage = page.getTotalPage();
			currentPageNo = currentPageNo > 1 ? (currentPageNo < totalPage ? currentPageNo : totalPage) : 1;
			if (totalCount > 0) {
				otherParams = otherParams == null ? "" : "&" + otherParams;

				Map<String, Object> context = new HashMap<String, Object>();
				context.put("_pre", new Integer(currentPageNo - 1));
				context.put("_current", new Integer(currentPageNo));
				context.put("_next", new Integer(currentPageNo + 1));
				context.put("_totalCount", new Integer(totalCount));
				context.put("_totalPage", new Integer(totalPage));
				context.put("_pageSize", new Integer(pageSize));
				context.put("_action", action);
				context.put("_otherParams", otherParams);
				context.put("_pageNoStr", PageInfo.CURRENT_PAGE_NAME);
				VelocityEngineUtils.mergeTemplate(engine, vm, context, writer);
			}
		} catch (Exception e) {
			log.error(this.getClass().getName() + "#end Exception!", e);
		}
		return super.end(writer, "");
	}

	/**
	 * 
	 * @return
	 */
	public String getOtherParams() {
		return otherParams;
	}

	/**
	 * 
	 * @param otherParams
	 */
	public void setOtherParams(String otherParams) {
		this.otherParams = otherParams;
	}

	/**
	 * 
	 * @return
	 */
	public String getVm() {
		return vm;
	}

	/**
	 * 
	 * @param vm
	 */
	public void setVm(String vm) {
		this.vm = vm;
	}

}
